<?php

declare (strict_types=1);


namespace App\Models\GameDB\Frag;

use App\Models\MainDB\Gift;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;

class GiftTemplate extends Model
{
    protected $connection = 'mysql_game';
    protected $table = 'lottery_frag_gift_template';
    //protected $fillable = [];
    protected $guarded = [];

    //protected $casts = ['id' => 'int', 'user_id' => 'integer', 'amount' => 'integer', 'balance' => 'integer', 'created_at' => 'datetime', 'updated_at' => 'datetime'];

    public function one(array $filters)
    {
        return self::query()->where($filters)->first();
    }

    public function listAll(array $filters, $fields, $flag = 0)
    {
        if($flag == 1) {
            $list   = (new \App\Models\GameDB\Frag\PoolGroup())::query()->from("game.lottery_frag_pool_group as a")
                ->leftJoin("game.lottery_frag_pool_template as b", 'a.id', '=', 'b.group_id')
                ->leftJoin("game.lottery_frag_gift_template as c", 'b.gift_template_id', '=', 'c.id')
                ->select("c.gift_id")
                ->where(['a.status' => 1])->distinct()->get();
            return $list;
        }
        return self::query()->where($filters)->select($fields)->get();
    }

    public function getGiftListByIds(array $templateIds, array $fields)
    {
        return self::query()->select($fields)->whereIn('id', $templateIds)->get();
    }

    public function gift()
    {
        return $this->hasOne(\App\Models\MainDB\Gift::class, 'id', 'gift_id');
    }


    public function getSpecialGiftList()
    {
        $key    = "game:frag:special_gift";
        $list   = [];
        if(app("redis")->exists($key)) {
            $list   = json_decode(app("redis")->get($key), true);
        }
        if(empty($list)) {
            $list   = self::query()->from("game.lottery_frag_gift_template as a")
                ->leftJoin("main.ln_gift as b",'a.gift_id','=','b.id')
                ->select("b.name", "b.picture")
                ->where('a.is_special', '=', 1)
                ->orderBy('a.id')
                ->get();
        }
        if(empty($list)) {
            return [];
        }
        app("redis")->set($key, json_encode($list, JSON_UNESCAPED_UNICODE),'ex', 60 * 60 * 24);
        return $list;
    }

}
